import { requestAnimationFrame, cancelAnimationFrame } from './util'

class Scene {
  constructor(cfg = {}) {
    this.cfg = cfg

    if (!cfg.target) {
      throw('Need element!')
      return
		}

    this.t = cfg.target
    this.current = {
      x: null,
      y: null
    }

    this.canvas = document.createElement('canvas')
    this.context = this.canvas.getContext('2d')

    const w = this.w = this.t.clientWidth
    const h = this.h = this.t.clientHeight

    this.context.width = w
    this.canvas.width = w
    this.context.height = h
    this.canvas.height = h

    cfg.target.append(this.canvas)

    this.drawCanvas()
    this.binEvent()
  }

  requestFrame(func) {
    this.tid = requestAnimationFrame(() => func.call(this));
  }

  drawCanvas() {
    const {
      w,
      h,
      context: ctx,
      current
    } = this;

    ctx.clearRect(0, 0, w, h);

    // const x = Math.random() * w;
    // const y = Math.random() * h;

    const x = current.x;
    const y = current.y;

    if (!x || !y) {
      this.requestFrame(this.drawCanvas);
      return;
    }

    // ctx.lineTo(x, y)
    // ctx.stroke()

    ctx.beginPath();
    ctx.fillStyle = `hsl(0, 65%, ${Math.random()*100 >> 0}%)`
    ctx.arc(x, y, Math.random()*50, 0, 2*Math.PI, true);
    ctx.closePath();
    ctx.fill();

    this.requestFrame(this.drawCanvas);
  }

  destroy() {
    cancelAnimationFrame(this.tid);
  }

  binEvent() {
    this.t.onmousemove = e => this.onmousemove(e);
    this.t.onmouseout = e => this.onmouseout(e);
  }

  onmousemove(e) {
    this.current.x = e.clientX - this.t.offsetLeft + document.scrollingElement.scrollLeft;
    this.current.y = e.clientY - this.t.offsetTop + document.scrollingElement.scrollTop;
  }

  onmouseout() {
    this.current.x = null;
    this.current.y = null;
  }
}


if (ENV === 'development') {
  console.log(`%c[${ENV}]`, 'color: blue', 'started!')

  new Scene({
    target: document.querySelector('.scene'),
    image: 'https://goss1.vcg.com/creative/vcg/400/new/VCG41N913056334.jpg'
  })
}
